<?php

// This is the business model of users and groups

class User_group_model extends Model {

	function User_group_model()
	{
		parent::Model();
		$this->obj =& get_instance();
	}

	// Test if latest schema, user_group
	function valid_db() 
	{
		return $this->db->table_exists('uzantoj');
	}

	/*
	|--------------------------------------------------------------------------
	|				functions of ci_usergroup (joined) table
	|--------------------------------------------------------------------------
	*/
	
	// a function to join tables, intended private
	function _joinTables()
	{
		// needs no prefix !?!
		$prefix = '';

		$this->db->use_table('uzantgrupoj');
		$this->db->join('uzantoj', $prefix.'uzantgrupoj.uz_id = '.$prefix.'uzantoj.uz_id');
		$this->db->join('grupoj', $prefix.'uzantgrupoj.grup_id = '.$prefix.'grupoj.grup_id');
		
		$prefix = $this->obj->db->dbprefix;
		return $prefix;
	}

	// get everything listed in order
	function listAllInfo($order = 'nomo')
	{
		$this->_joinTables();

		$this->db->orderby($order);
		return $this->db->get();
	}
	
	// Get user and group info for $userid
	function listUserInfo($userid)
	{
		$prefix = $this->_joinTables();
		
		$this->db->where ($prefix.'uzantoj.uz_id', $userid);
		$query = $this->db->get();
		return $query->row();
	}

	/**
	* Get a list of the groups that the supplied username belongs to
	*
	* @param array $username Username to find the groups he belongs to
	* @return array Group names the specified user belongs to
	*/

	function groupsOfUser($username)
	{

		$prefix = $this->_joinTables();

		$this->db->select($prefix.'grupoj.grupnomo');
		$this->db->where($prefix.'uzantoj.nomo', $username);
		$query = $this->db->get();
		$result = $query->result();
		$groups = array();
		if($result){
			foreach($result as $row){
				$groups[] = $row->grupnomo;
			}
		}
		return $groups;
	}

	/**
	* Returns an array of users belonging to specified group
	*
	* @param array $groupname Name of group you want
	* @return array Users belonging to the group specified
	*/
	function usersInGroup($groupname)
	{

		$prefix = $this->_joinTables();

		//check select()
		$this->db->select($this->obj->db->dbprefix.'uzantoj.nomo');
		$this->db->where($this->obj->db->dbprefix.'grupoj.grupnomo', $groupname);
		$query = $this->db->get();
		$result = $query->result();
		$users = array();
		if($result){
			foreach($result as $row){
				$users[] = $row->nomo;
			}
		}
		return $users;
	}

	/*
	|--------------------------------------------------------------------------
	|				functions of ci_usergroup table
	|--------------------------------------------------------------------------
	*/

	function usersInGroupByID($groupid){
		$this->db->use_table('uzantgrupoj');
		$this->db->select('uz_id');
		$this->db->where('grup_id', $groupid);
		return $this->db->get();
	}

	/**
	* Function to put a user in an exclusive group (no belonging to multiple groups)
	*/
	function putuseringroup($username, $groupname){

		$userid = $this->getUserId($username);
		$groupid = $this->getgroupid($groupname);
		$this->db->use_table('uzantgrupoj');

		// Remove user form all groups first
		$this->db->where('uz_id', $userid);
		$this->db->delete('grup_id'); 

		// Add user to group
		$data = array( 'grup_id' => $groupid, 'uz_id' => $userid );
		$this->db->insert('uzantgrupoj', $data); 
	}

	// get this user's group memembership
	function groups_this_user() 
	{
		if ($this->userauth->loggedin()) {
			$thisuser = $this->session->userdata('username');
			return $this->groupsOfUser($thisuser);
		} else { return FALSE; }
	}

	/*
	|--------------------------------------------------------------------------
	|				functions envolving multiple tables
	|--------------------------------------------------------------------------
	*/

	/**
	* Add a user to the DB
	*
	* @param array $userarray Array containing the user attributes
	* @return int 0:Not added,1:User added,2:Already exists
	*/
	function addUser($username, $password,$email, $enabled, $group){
		if(!$username || !$password || !$email || !$enabled || !$group){
			// something isn't there.
			// probably should also run some validation here....
			return 0;
		} elseif (!$this->userExists($username)){
			$password = md5($password);
			// insert user
			$userinfo = array(
						   'nomo' => $username,
						   'pasvorto' => $password,
						   //'fullname' => $fullname,
						   'retposxto' => $email,
						   'cxuaktiva' => $enabled
						);

			$this->db->insert('uzantoj', $userinfo); // to to users table
			$this->db->insert('uzantgrupoj', array('uz_id'=>$this->db->insert_id(), 'grup_id'=>$group));	// add to usergroups
			return 1; // User added
		} else {
			return 2; // User already exists
		}
	}

	function editUser ($userid, $username, $password, $email, $enabled, $group)
	{
			// user info
			$userinfo = array(
						   'nomo' => $username,
						 //  'fullname' => $fullname,
						   'retposxto'    => $email,
						   'cxuaktiva'  => $enabled
						);
			// if the password was filled out, add it to the array.
			if ($password != '') {
				$userinfo['pasvorto'] = md5($password);
			}
			
			$this->db->where('uz_id', $userid);
			$this->db->update('uzantoj', $userinfo);  // users table
			$this->db->where('uz_id', $userid);
			return $this->db->update('uzantgrupoj', 
						array('grup_id'=>$group));	// add to usergroups
	}

	/**
	* Remove a user
	*
	* Note: function also removes the user from all groups they are a member of
	*
	* @param string $username Username of the user to remove
	* @return bool
	*/
	function removeUser($username){
		if($username == $this->session->userdata('username')) {
			// Exit if delete object is same as session user (same person)
			log_message('info', 'User change: User '.$username.' tried to delete themself.');
			show_error( $this->lang->line('ua_error_no_suicide') );
			exit();
		}
		if($this->userExists($username)) {
			// Delete group			
			$this->db->where('uz_id', $this->getUserId($username));
			$this->db->delete('uzantgrupoj'); 
			// Delete user
			$this->db->where('uz_id', $this->getUserId($username));
			$this->db->delete('uzantoj'); 
			// Delete rememberMe
			$this->obj->remember_me->removeRememberMe ($username);
			return TRUE;
		} else {
			// User didn't exist in the first place!
			return FALSE;
		}
	}

	/*
	|--------------------------------------------------------------------------
	|		utility function used for either ci_user or ci_group table
	|--------------------------------------------------------------------------
	*/

	/**
	* List all users or all groups depending on parameter
	*
	* @param string $option Can be one of:
	* 'users', 'groups'
	* @return array Array containing list of users/groups
	*/	
	function listUG($option){
		switch($option){
			case 'users':
				$this->db->use_table('uzantoj');
				$this->db->select('uz_id, nomo, retposxto, lastaeniro, cxuaktiva');
				$arr = $this->db->get();
				break;
			case 'groups':
				$this->db->use_table('grupoj');
				$this->db->select('grup_id, grupnomo, priskribo');
				$arr = $this->db->get();
				break;
		}
		return $arr;
	}

	/*
	|--------------------------------------------------------------------------
	|				functions using only ci_user table
	|--------------------------------------------------------------------------
	*/

	function testLogin($username, $password) {
		// test if valid user
		if ( $this->userExists($username) == TRUE ) {
			$this->db->use_table('uzantoj');
			$this->db->select('uz_id');
			$this->db->where('nomo', $username);
			$this->db->where ('pasvorto', $password);
			$result = $this->db->get();
			if ($result->num_rows() > 0) {
				return TRUE;
			} else { return FALSE; }
		} else { return FALSE; }
	}

	function dateStampLogin($username) {
		$this->db->where('nomo', $username);
		$datestamp = date("Y-m-d H:i:s");
		$this->db->set('lastaeniro', $datestamp); 
		$this->db->update('uzantoj');
		log_message('debug',"Last login by ".$username.": ".$datestamp);
	}

	/**
	* Checks to see if the supplied user exists in the DB
	*
	* @param string $username Username to look up
	* @return bool True if user exists
	*/
	function userExists($username){
		$this->db->use_table('uzantoj');
		$this->db->select('uz_id');
		$this->db->where('nomo', $username);
		$result =  $this->db->get();
		return ($result->num_rows() == 1) ? TRUE : FALSE;
	}

	function getUserName($userid){
		$this->db->use_table('uzantoj');
		$this->db->select('nomo');
		$this->db->where('uz_id', $userid);
		$query = $this->db->get();
		$query = $query->row();
		return $query->nomo;
	}

	function getUserId($username) {
		$this->db->use_table('uzantoj');
		$this->db->select('uz_id');
		$this->db->where('nomo', $username);
		$query = $this->db->get();
		$query = $query->row();
		return $query->uz_id;
	}

	/**
	* Check if account is enabled or not
	*
	* @param string $user Single username
	* @return bool User is enabled:true
	*/
	function enabled($username){
		$this->db->use_table('uzantoj');
		$this->db->select('cxuaktiva');
		$this->db->where('nomo', $username);
		$query = $this->db->get();
		$row = $query->row();
		$ret = ($row->enabled == 1) ? TRUE : FALSE;
		return $ret;
	}
	
	/*
	|--------------------------------------------------------------------------
	|				functions using only ci_group table
	|--------------------------------------------------------------------------
	*/

	function addGroup ($groupname, $groupdescription) {
		$this->db->set('grupnomo', $groupname); 
		$this->db->set('priskribo', $groupdescription);
		return $this->db->insert('grupoj');
	}

	function editGroup ($groupid, $groupname, $groupdescription) {
		// group info
		$groupinfo = array(
					   'grupnomo' => $groupname,
					   'priskribo' => $groupdescription
					);		
		$this->db->where('grup_id', $groupid);
		$this->db->update('grupoj', $groupinfo);  // users table
		if ($this->db->affected_rows() == 1) {
			return true;
		} else {
			return false;
		}
	}

	function removeGroup($groupid){
		$query = $this->usersInGroupByID($groupid);
		$numberOfGroupMembers = $query->num_rows();
		if ($numberOfGroupMembers == 0) {
			$this->db->where('grup_id', $groupid);
			return $this->db->delete('grupoj'); // remove group info
		} else {
			return 2;
		}
	}

	function listGroupInfo($groupid) {
		$this->db->use_table('grupoj');
		$this->db->where ('grup_id', $groupid);
		$query = $this->db->get();
		return $query->row();
	}

	function getgroupid($groupname){
		$this->db->use_table('grupoj');
		$this->db->where ('grupnomo', $groupname);
		$query = $this->db->get();
		$row = $query->row();
		return $row->grup_id;
	}
	
	function getgroupname($groupid){
		$this->db->use_table('grupoj');
		$this->db->where ('grup_id', $groupid);
		$query = $this->db->get();
		$row = $query->row();
		return $row->grupnomo;
	}
}

?>